<script setup lang="ts">
import type { ApproveRequest } from '@/api/types/workflow'
import { onLoad } from '@dcloudio/uni-app'
import { reactive, ref } from 'vue'
import { approveTask } from '@/api/workflow'
import ApprovalActionFooter from './components/ApprovalActionFooter.vue'
import ApprovalOpinion from './components/ApprovalOpinion.vue'

// 页面配置
definePage({
  style: {
    navigationBarTitleText: '审批通过',
    navigationBarTextStyle: 'black',
  },
})

// 页面参数
const params = ref<{ id?: string, title?: string }>({})

// 表单数据
const formData = reactive({
  comment: '同意', // 审批意见
  copyUserIds: [] as string[], // 抄送人员ID列表
})

// 加载状态
const loading = ref(false)

// 监听页面加载，获取参数
onLoad((options) => {
  params.value = options

  // 如果有title参数，设置导航栏标题
  if (options.title) {
    uni.setNavigationBarTitle({
      title: `${decodeURIComponent(options.title as string)}-同意`,
    })
  }
})

// 更新审批意见
function updateComment(value: string) {
  formData.comment = value
}

// 审批操作函数
async function handleApprove() {
  // 验证表单
  if (!formData.comment) {
    uni.showToast({
      title: '请输入审批意见',
      icon: 'none',
    })
    return
  }
  try {
    loading.value = true

    // 构造请求参数
    const requestData: ApproveRequest = {
      id: params.value.id || '',
      reason: formData.comment,
      copyUserIds: formData.copyUserIds,
    }
    console.log('审批通过操作', requestData)
    // 调用审批同意API
    const res = await approveTask(requestData)

    if (res.data) {
      setTimeout(() => {
        // 跳转到结果页面
        uni.navigateBack()
      }, 1500)
    }
    else {
      uni.showToast({
        title: res?.msg || '审批失败，请重试',
        icon: 'none',
      })
    }
  }
  catch (error) {
    console.error('审批通过失败:', error)
    uni.showToast({
      title: '审批失败，请稍后重试',
      icon: 'none',
    })
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <view class="approval-container h-screen bg-gray-100">
    <!-- 审批意见输入 - 使用组件 -->
    <ApprovalOpinion
      v-model="formData.comment"
      placeholder="请输入审批意见（选填）"
      title="审批意见："
      @update:model-value="updateComment"
    />

    <!-- 抄送 -->
    <SelectedUsers
      v-model="formData.copyUserIds"
      title="选择抄送人员"
    />

    <!-- 操作按钮 -->
    <ApprovalActionFooter
      :button-text="loading ? '处理中...' : '同意'"
      button-type="success"
      :loading="loading"
      @confirm="handleApprove"
    />
  </view>
</template>
